#ifndef ILOG_H
#define ILOG_H

#include "qmutex.h"
#include <QtGlobal>
#include <QDateTime>
#include <QDebug>
#include <QThread>
#include <QCoreApplication>
#include <qfile.h>
#include <QDir>

#define DT_FORMAT_YMDHMSZ "yyyy-MM-dd hh:mm:ss zzz"
#define CURRENT_DT QString("[%1]").arg(QDateTime::currentDateTime().toString(DT_FORMAT_YMDHMSZ))
#define CURRENT_TR QString("[%1]").arg(quintptr(QThread::currentThread()))

#define LOG_DEBUG() qDebug()
#define LOG_INFO() qInfo()
#define LOG_WARN() qWarning()
#define LOG_CRIT() qCritical()

inline void outPutMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    qDebug()<< context.function;
    const char *function = context.function ? context.function : "";
    QString typeInfo = "";
    FILE *__stream = stdout;
    switch (type) {
    case QtDebugMsg:
        typeInfo = "[Debug]";
        __stream = stderr;
        break;
    case QtInfoMsg:
        typeInfo = "[Info]";
        break;
    case QtWarningMsg:
        typeInfo = "[Warn]";
        __stream = stderr;
        break;
    case QtCriticalMsg:
        typeInfo = "[Crit]";
        __stream = stderr;
        break;
    case QtFatalMsg:
        typeInfo = "[Fatal]";
        __stream = stderr;
        break;
    }
    QString typeStr = QString("%1").arg(typeInfo , -7 , QChar(' '));
    fprintf(__stream, "%s [%u] %s %s:%u %s\n", CURRENT_DT.toLocal8Bit().constData(),
            quintptr(QThread::currentThread()),
            typeStr.toLocal8Bit().constData(),
            function ,
            context.line , localMsg.constData());
    QString message = QString("%1 [%2] %3 %4 %5 %6").arg(CURRENT_DT).arg(quintptr(QThread::currentThread())).arg(typeStr)
                          .arg(function).arg(context.line).arg(msg);
    //    fflush(stderr);
    static QMutex mutex;
    static QFile file;
    static QTextStream textStream;
    static uint count = 0;
    static const uint maxCount = 512;
    Q_UNUSED(context)
    QDateTime dt = QDateTime::currentDateTime();

    // 每小时一个文件
    QString fileNameDt = dt.toString(QStringLiteral("yyyy-MM-dd_hh"));

    // 每分钟一个文件
    //  QString fileNameDt = dt.toString("yyyy-MM-dd_hh_mm");

    QString contentDt = dt.toString(QStringLiteral("yyyy-MM-dd hh:mm:ss"));
//    QString message = QStringLiteral("%1 %2").arg(contentDt).arg(msg);
    QString  dirPath = QCoreApplication::applicationDirPath() + "/log";
    if (!QDir(dirPath).exists())
    {
        QDir().mkpath(dirPath);
    }
    QString newfileName = QStringLiteral("%1/%2.log").arg(dirPath).arg(fileNameDt);
    mutex.lock();
    if (file.fileName() != newfileName)
    {
        if (file.isOpen())
        {
            file.close();
        }
        file.setFileName(newfileName);
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        textStream.setDevice(&file);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        textStream.setEncoding(QStringConverter::Utf8);
#else
        textStream.setCodec("UTF-8");
#endif
    }
    textStream << message << "\r\n";
    textStream.flush();
    count += message.length();
    if (count >= maxCount)
    {
        file.close();
        file.open(QIODevice::WriteOnly | QIODevice::Append);
    }
    mutex.unlock();
}

inline void setOutput()
{
    qInstallMessageHandler(outPutMessage);
    setbuf(stderr , nullptr);
    setbuf(stdout , nullptr);
}

namespace Log {
inline void init()
{
    setOutput();
}
}

#endif // ILOG_H
